
<template>
    <el-dialog v-model="showDialog" :title="drawerTitile" :close-on-click-modal="true" :destroy-on-close="destroyOnClose"
        @close="clean">
        <div class="formDrawer">
        <!-- 分配角色组件 -->
            <el-scrollbar max-height="160px" class="roleList-scrollbar">
                <el-table ref="assignTableRef" :data="assignTable" @select-all="selectAll" v-loading="loading"
                    border>
                    <el-table-column size="small" type="selection" align="center">
                        <template #default="scope">
                            <el-checkbox v-model="scope.row.checked" @change="select" />
                        </template>
                    </el-table-column>
                    <el-table-column property="id" label="id" width="120" />
                    <el-table-column property="roleName" label="角色名称" />
                    <el-table-column property="roleKey" label="角色备注" />
                </el-table>
            </el-scrollbar>
            <el-pagination class="pagination" background layout="prev, pager, next" :total="1000" v-model:current-page="page.pi" :page-count="page.ps"
            @current-change="handleCurrentChange"  />
        </div>
        
        <div class="actions">
                <el-button type="primary" @click="submit" :loading="loading">确定</el-button>
                <el-button type="default" @click="close">取消</el-button>
        </div>
    </el-dialog>
</template>
<script setup>
import { ref, onMounted, computed, reactive, toRef, nextTick} from "vue"
import {
    toast
} from '~/composables/util.js'
import User from '~/api/user.js'
import Role from '~/api/role.js'

const loading = ref(false)
const showDialog = ref(false)
const props = defineProps({
    destroyOnClose: {
        type: Boolean,
        default: false
    },
    data: {
        type: Object, // 假设初始值是一个对象
        default: () => ({})// 默认为空对象
    },
    drawerTitile: {
        type: String,
        default: '分配角色'
    }

})

//角色分配操作开始
const assignFormRef = ref(null)
const assignSearchForm = reactive({})
const assignTableRef = ref(null)
const assignTable = ref([])
const roleids = ref([])
const uid = ref('')

const page = reactive({
    pi:1, //页码
    ps:5  //页数(可以自己设定)
})
const value = toRef(props.data).value

const open = async function () {
    // console.log(value)
    showDialog.value = true
    loading.value = false
    loading.value = true
    
    //设置列表中进行分配角色的用户id
    await nextTick(()=>{
        uid.value = value.value.id
    })

    await InitRole()
}

// 关闭
const close = () => showDialog.value = false

//初始化数据函数
const InitRole = async function () {
    let roleids
    roleids = []
    const data = {...page}
    console.log('传递参数为')
    console.log(data)

    loading.value = true

    //查看所有的角色信息
    await Role.getRole(data).then(res => {
        console.log(res)
        assignTable.value = res.data.data.records   
    }).catch(err=>{
        console.log(err)
    })
    // console.log(assignTable.value)

    //根据用户id查询到该用户对应的所有角色id
    value.value.role.forEach(item => {
        roleids.push(item.id)
    })
    // console.log(roleids)


    //进行对比数据,然后改变checked
    await roleids.forEach(async (item1) => {
        assignTable.value.forEach(item2 => {
            if (item1 === item2.id) {
                item2.checked = true
            }
        })
    })
    console.log(assignTable.value)
    loading.value = false
}

const handleCurrentChange = function(){
    InitRole()
}


//选中之后的操作
//反选
const select = function () {
    assignTable.value.forEach(t => {
        assignTableRef.value.toggleRowSelection(t, t.checked)
    })
}
//全选
const selectAll = function (row) {
    assignTable.value.forEach(t => {
        t.checked = !!row[0]
    })
}
//提交
const submit = async function () {
    //这里将checked为true的值拿出来进行处理
    loading.value = true
    let roleIds,userId
    userId = uid.value
    roleIds = []
    assignTable.value.forEach(t => {
        if (t.checked) {
            roleIds.push(t.id)
        }
    })
    let data = {
        userId,
        roleIds
    }

    console.log('提交的数据为')
    console.log(data)

    await User.updateUserRole(data).then(res => {
        console.log(res)
        if(res.data.data !== null){
            toast('修改成功','success',false,3000)   
            close()
            loading.value = false
        }else{
            toast(res.data.msg,'warning',false,3000)
        }
    }).finally(() => {
        loading.value = false
    })
}
//角色分配操作结束


//暴露clean方法
const emit = defineEmits(["clean"])
const clean = () => {
    emit("clean")
}

// 向父组件暴露以下方法
defineExpose({
    open,
    close
})

</script>
<style>
.formDrawer {
    width: 100%;
    height: 100%;
    position: relative;
    @apply flex flex-col;
}

.formDrawer .body {
    flex: 1;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 50px;
    overflow-y: auto;
}

.formDrawer .actions {
    height: 50px;
}
.formDrawer .pagination{
    margin: 20px auto;
}
.roleList-scrollbar {
    max-width: 800px;
    max-height: 160px;
}
</style>